package mysql

import (
	"fmt"
	"net/url"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

var (
	db                *gorm.DB
	ErrRecordNotFound = gorm.ErrRecordNotFound
)

var (
	host     = "127.0.0.1"
	port     = 3306
	username = "root"
	password = "password"
	dbname   = "transfinite"
	debug    = false
	salve    = false
)

func InitDefault() {

}

func Init(_username, _password, _host string, _port int, _dbname string, _debug, _salve bool) {
	host = _host
	port = _port
	username = _username
	password = _password
	dbname = _dbname
	debug = _debug
	salve = _salve
	var err error
	db, err = newDBCon()
	if err != nil {
		panic(err)
	}
}

func getConn() *gorm.DB {
	if db == nil {
		db, _ = newDBCon()
	}
	return db

}

func newDBCon() (*gorm.DB, error) {
	t, _ := time.LoadLocation("Local")
	db, err := gorm.Open("mysql",
		fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=%s",
			username,
			password,
			host,
			port,
			dbname,
			url.QueryEscape(t.String())))
	if err != nil {
		_ = mysqlFatalLog(map[string]interface{}{
			"host":     host,
			"port":     port,
			"username": username,
			"password": password,
			"dbname":   dbname,
			"debug":    debug,
			"salve":    salve,
		}, err)
		return nil, err
	}
	if salve {
		// 腾讯数据库实例从库读操作插件
		// gorm:query_front_option gorm官方目前并不支持，需自修改代码
		// 该插件即使使用官方库不支持该操作也不会产生影响
		db.Callback().Query().Before("gorm:query").Register("publish:before_query", func(s *gorm.Scope) {
			s.Set("gorm:query_front_option", "/*slave*/ ")
		})
		db.Callback().RowQuery().Before("gorm:row_query").Register("publish:beGetMerchantInfoByAppidfore_row_query", func(s *gorm.Scope) {
			s.Set("gorm:query_front_option", "/*slave*/ ")
		})
	}
	if debug {
		db.LogMode(true)
		db = db.Debug()
	} else {
		db.LogMode(false)
	}

	db.DB().SetMaxOpenConns(0)
	db.DB().SetMaxIdleConns(0)
	db.DB().SetConnMaxLifetime(time.Second * 10)

	return db, err
}

func StopMysql() {
	if db != nil {
		db.Close()
	}
}
